import { useMutation, useQueryClient } from "@tanstack/react-query";
import { userAPI } from "@/api/user";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useErrorHandler } from "@/lib/error-handler";
import type { ErrorResponse, Response } from "@/types/response";
import type { AxiosError } from "axios";

/**
 * 发送邮箱更新验证码 hooks
 */
export const useSendEmailUpdateCaptcha = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();

  const sendEmailUpdateCaptchaMutation = useMutation({
    mutationFn: userAPI.sendEmailUpdateCaptcha,
    onSuccess: (response: Response) => {
      if (response.code === 200) {
        toast.success(t("Verification code sent"), {
          description:
            response.message ||
            t(
              "A verification code has been sent to your email. Please check your inbox.",
              {
                defaultValue:
                  "A verification code has been sent to your email. Please check your inbox.",
              }
            ),
          duration: 5000,
        });
      } else {
        toast.error(t("Failed to send verification code"), {
          description:
            response.message ||
            t(
              "An error occurred while sending verification code. Please try again."
            ),
          duration: 5000,
        });
      }
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      const errorResult = errorHandler.handleApiError(error);

      if (errorResult.type === "warning") {
        toast.warning(t("Failed to send verification code"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Failed to send verification code"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Send email update captcha error:", error);
    },
  });

  return {
    sendEmailUpdateCaptcha: sendEmailUpdateCaptchaMutation.mutate,
    sendEmailUpdateCaptchaAsync: sendEmailUpdateCaptchaMutation.mutateAsync,
    isSendingCaptcha: sendEmailUpdateCaptchaMutation.isPending,
    sendCaptchaError: sendEmailUpdateCaptchaMutation.error,
  };
};

/**
 * 更新邮箱 hooks
 */
export const useUpdateEmail = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const queryClient = useQueryClient();

  const updateEmailMutation = useMutation({
    mutationFn: userAPI.updateEmail,
    onSuccess: (response: Response) => {
      if (response.code === 200) {
        // 使缓存失效，重新获取用户信息
        queryClient.invalidateQueries({ queryKey: ["user"] });
        toast.success(
          t("Email updated successfully", {
            defaultValue: "Email updated successfully",
          }),
          {
            description:
              response.message ||
              t("Your email has been updated successfully.", {
                defaultValue: "Your email has been updated successfully.",
              }),
            duration: 5000,
          }
        );
      } else {
        toast.error(t("Email update failed"), {
          description:
            response.message ||
            t("An error occurred during email update. Please try again."),
          duration: 5000,
        });
      }
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      const errorResult = errorHandler.handleApiError(error);

      if (errorResult.type === "warning") {
        toast.warning(t("Email update failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Email update failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Update email error:", error);
    },
  });

  return {
    updateEmail: updateEmailMutation.mutate,
    updateEmailAsync: updateEmailMutation.mutateAsync,
    isUpdatingEmail: updateEmailMutation.isPending,
    updateEmailError: updateEmailMutation.error,
  };
};
